﻿/*
*┌────────────────────────────────────────────────┐
*│　描    述：HospitalBLL                                                   
*│　作    者： (Jxw)                                             
*│　版    本：1.0                                              
*│　创建时间：2020/8/21 10:20:10                        
*└────────────────────────────────────────────────┘
*/
using Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utility;

namespace BLL
{
    public class HospitalBLL
    {
        public RetInfo<List<Hashtable>> GetHospitalList(string name, string skill,
            string level, string acceptable)
        {
            RetInfo<List<Hashtable>> ri = new RetInfo<List<Hashtable>>(true);
            try
            {
                List<SqlParameter> spList = new List<SqlParameter>();
                if (!string.IsNullOrEmpty(skill))
                {
                    StringBuilder dicSB = new StringBuilder(@"
select * from TZDictionary tzd where 名称=@skill");
                    SqlParameter dicSP = new SqlParameter("@skill", skill);
                    DataSet dicDS = DataSetUtility.GetDataSetFromCDB(dicSB, dicSP);
                    if (dicDS.Tables.Count > 0 && dicDS.Tables[0].Rows.Count > 0)
                    {
                        DataRow dr = dicDS.Tables[0].Rows[0];
                        //string id = dr["编码"].ToString();
                        spList.Add(new SqlParameter("@skill", "%" + dr["编码"] + "%"));
                    }
                }

                StringBuilder sb = new StringBuilder(@"
select thbi.医院名称,thbi.医院简称,thbi.医院编码,tzd.名称 as 医院等级,
thrti.留观使用量,thrti.留观室床位,thbi.经度,thbi.纬度
from [dbo].[THospitalBaseInfo] thbi
left join [dbo].[THospitalRealTimeInfo] thrti on thbi.医院编码=thrti.医院编码
left join TZDictionary tzd on thbi.医院级别=tzd.编码 and tzd.类型编码='Hospital-Level'
where 1=1 and thbi.是否有效=1
");

                if (!string.IsNullOrEmpty(name))
                {
                    sb.Append(@" and thbi.医院名称 like @name");
                    spList.Add(new SqlParameter("@name", "%" + name + "%"));
                }
                if (!string.IsNullOrEmpty(skill))
                {
                    sb.Append(@" and thbi.医院特长 like @skill");
                }
                if (!string.IsNullOrEmpty(level))
                {
                    sb.Append(@" and thbi.医院级别=@level");
                    spList.Add(new SqlParameter("@level", level));
                }
                if (!string.IsNullOrEmpty(acceptable))
                {
                    if (Convert.ToBoolean(acceptable))
                    {
                        sb.Append(@" order by thbi.突发事件接诊能力 desc");
                    }
                }
                DataSet ds = DataSetUtility.GetDataSetFromCDB(sb, spList.ToArray());
                List<Hashtable> list = new List<Hashtable>();
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    Hashtable ht;
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        ht = new Hashtable();
                        ht.Add("Name", dr["医院名称"]);
                        ht.Add("SimName", dr["医院简称"]);
                        ht.Add("Code", dr["医院编码"]);
                        ht.Add("Level", dr["医院等级"]);
                        ht.Add("RoomUsed", dr["留观使用量"]);
                        ht.Add("Rooms", dr["留观室床位"]);
                        int sum = Convert.ToInt32(dr["留观室床位"] is DBNull ? 0 : dr["留观室床位"]);
                        int used = Convert.ToInt32(dr["留观使用量"] is DBNull ? 0 : dr["留观使用量"]);
                        double percent = sum == 0 ? 0 : (used * 100.0 / sum);
                        percent=percent > 100 ?100 : percent;
                        ht.Add("Degree", Math.Round(percent, 0, MidpointRounding.AwayFromZero));
                        ht.Add("Longitude", dr["经度"]);
                        ht.Add("Latitude", dr["纬度"]);
                        ht.Add("Color", ConvertDegreeToColor(percent));
                        list.Add(ht);
                    }
                }
                if (list.Count > 0)
                {
                    ri.data = list;
                }
                else
                {
                    ri.ret = false;
                    ri.res = "未获取到医院列表";
                }
            }
            catch (Exception ex)
            {
                ri.ret = false;
                ri.res = ex.Message;
                LogUtility.Error("HospitalBLL/GetHospitalList", ex.ToString());
            }
            return ri;
        }
        public string ConvertDegreeToColor(double degree)
        {
            string color = "";
            if (degree >= 100)
            {
                color = "#e51728";
            }
            else if (degree >= 70)
            {
                color = "#fca832";
            }
            else
            {
                color = "#01ded3";
            }
            return color;
        }

        public RetInfo<Hashtable> GetHospitalInfo(string id)
        {
            RetInfo<Hashtable> ri = new RetInfo<Hashtable>(true);
            try
            {
                SqlParameter sp = new SqlParameter("@ID", id);
                StringBuilder sb = new StringBuilder(@"
select thbi.突发事件接诊能力,thbi.突发事件一级接诊能力,thbi.突发事件二级接诊能力,
thbi.突发事件三级接诊能力,thrti.急诊开放状态,
thrti.急诊挂号人数,thbi.呼吸机,thbi.洗胃机,
thrti.抢救室床位,thrti.留观室床位,thrti.神内导管室,thrti.心内导管室,
thrti.三级患者等候人数,thrti.四级患者等候人数,
thrti.抢救室使用量,thrti.留观使用量,thrti.神内使用量,thrti.心内使用量
from [dbo].[THospitalBaseInfo] thbi
left join [dbo].[THospitalRealTimeInfo] thrti on thbi.医院编码=thrti.医院编码
where thbi.医院编码=@ID

select t.科室类型,tzd.名称 as 科室类型名称,t.科室名称,t.备注,t.是否24小时开放,t.急诊出诊医生数
from [dbo].[THospitalDepartment] t
left join TZDictionary tzd on t.科室类型=tzd.编码
where t.医院编码=@ID

select t.能力类型,tzd.名称 as 能力类型名称,t.能力名称,t.是否24小时开放,t.备注
from [dbo].[THospitalAbilityInfo] t
left join TZDictionary tzd on t.能力类型=tzd.编码
where t.医院编码=@ID
");
                DataSet ds = DataSetUtility.GetDataSetFromCDB(sb, sp);
                if (ds.Tables.Count > 0)
                {
                    Hashtable mainHT = new Hashtable();
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataRow dr = ds.Tables[0].Rows[0];
                        mainHT.Add("EmergencyAcceptable", dr["突发事件接诊能力"]);
                        List<Hashtable> EACHTList = new List<Hashtable>();
                        Hashtable firstEACHT = new Hashtable();
                        firstEACHT.Add("FirstAcceptable", dr["突发事件一级接诊能力"]);
                        firstEACHT.Add("APercent", DealDataToPercent(dr["突发事件一级接诊能力"], dr["突发事件接诊能力"]));
                        firstEACHT.Add("AName", "红");
                        firstEACHT.Add("AColor", "#e51728");
                        EACHTList.Add(firstEACHT);

                        Hashtable secondEACHT = new Hashtable();
                        secondEACHT.Add("SecondAcceptable", dr["突发事件二级接诊能力"]);
                        secondEACHT.Add("APercent", DealDataToPercent(dr["突发事件二级接诊能力"], dr["突发事件接诊能力"]));
                        secondEACHT.Add("AName", "黄");
                        secondEACHT.Add("AColor", "#fca832");
                        EACHTList.Add(secondEACHT);

                        Hashtable thirdEACHT = new Hashtable();
                        thirdEACHT.Add("ThirdAcceptable", dr["突发事件三级接诊能力"]);
                        thirdEACHT.Add("APercent", DealDataToPercent(dr["突发事件三级接诊能力"], dr["突发事件接诊能力"]));
                        thirdEACHT.Add("AName", "绿");
                        thirdEACHT.Add("AColor", "#2ee62e");
                        EACHTList.Add(thirdEACHT);

                        mainHT.Add("AcceptableList", EACHTList);

                        mainHT.Add("AidOpenState", dr["急诊开放状态"]);

                        List<Hashtable> AOHTList = new List<Hashtable>();
                        Hashtable GNHT = new Hashtable();
                        GNHT.Add("AOName", "急诊挂号人数");
                        GNHT.Add("AOValue", dr["急诊挂号人数"]);
                        AOHTList.Add(GNHT);

                        Hashtable BreathHT = new Hashtable();
                        BreathHT.Add("AOName", "呼吸机");
                        BreathHT.Add("AOValue", dr["呼吸机"]);
                        AOHTList.Add(BreathHT);

                        Hashtable ClearHT = new Hashtable();
                        ClearHT.Add("AOName", "洗胃机");
                        ClearHT.Add("AOValue", dr["洗胃机"]);
                        AOHTList.Add(ClearHT);

                        mainHT.Add("AcceptableOtherList", AOHTList);

                        List<Hashtable> EUHTList = new List<Hashtable>();

                        Hashtable aidBedHT = new Hashtable();
                        aidBedHT.Add("BedName", "抢救室床位");
                        aidBedHT.Add("BedUsed", dr["抢救室使用量"]);
                        aidBedHT.Add("BedSum", dr["抢救室床位"]);
                        double dblAidBed = DealDataToPercent(dr["抢救室使用量"], dr["抢救室床位"]);
                        aidBedHT.Add("BedColor", ConvertDegreeToColor(dblAidBed));
                        aidBedHT.Add("BedPercent", dblAidBed);
                        EUHTList.Add(aidBedHT);

                        Hashtable stayBedHT = new Hashtable();
                        stayBedHT.Add("BedName", "留观室床位");
                        stayBedHT.Add("BedUsed", dr["留观使用量"]);
                        stayBedHT.Add("BedSum", dr["留观室床位"]);
                        double dblStayBed = DealDataToPercent(dr["留观使用量"], dr["留观室床位"]);
                        stayBedHT.Add("BedColor", ConvertDegreeToColor(dblStayBed));
                        stayBedHT.Add("BedPercent", dblStayBed);
                        EUHTList.Add(stayBedHT);

                        Hashtable heartRoomHT = new Hashtable();
                        heartRoomHT.Add("BedName", "心内导管室");
                        heartRoomHT.Add("BedUsed", dr["心内使用量"]);
                        heartRoomHT.Add("BedSum", dr["心内导管室"]);
                        double dblHeartRoom = DealDataToPercent(dr["心内使用量"], dr["心内导管室"]);
                        heartRoomHT.Add("BedColor", ConvertDegreeToColor(dblHeartRoom));
                        heartRoomHT.Add("BedPercent", dblHeartRoom);
                        EUHTList.Add(heartRoomHT);

                        Hashtable nerveRoomHT = new Hashtable();
                        nerveRoomHT.Add("BedName", "神内导管室");
                        nerveRoomHT.Add("BedUsed", dr["神内使用量"]);
                        nerveRoomHT.Add("BedSum", dr["神内导管室"]);
                        double dblNerveRoom = DealDataToPercent(dr["神内使用量"], dr["神内导管室"]);
                        nerveRoomHT.Add("BedColor", ConvertDegreeToColor(dblNerveRoom));
                        nerveRoomHT.Add("BedPercent", dblNerveRoom);
                        EUHTList.Add(nerveRoomHT);

                        mainHT.Add("EUList", EUHTList);

                        List<Hashtable> PLHTList = new List<Hashtable>();

                        Hashtable threePLHT = new Hashtable();
                        threePLHT.Add("PLName", "三级患者等候人数");
                        threePLHT.Add("PLVal", dr["三级患者等候人数"]);
                        PLHTList.Add(threePLHT);

                        Hashtable fourPLHT = new Hashtable();
                        fourPLHT.Add("PLName", "四级患者等候人数");
                        fourPLHT.Add("PLVal", dr["四级患者等候人数"]);
                        PLHTList.Add(fourPLHT);

                        mainHT.Add("PLList", PLHTList);
                    }
                    if (ds.Tables[1].Rows.Count > 0)
                    {
                        List<HospitalDepartmentInfo> HDIList = new List<HospitalDepartmentInfo>();
                        HospitalDepartmentInfo HDIInfo;
                        foreach (DataRow dr in ds.Tables[1].Rows)
                        {
                            HDIInfo = new HospitalDepartmentInfo();
                            HDIInfo.name = dr["科室名称"].ToString();
                            HDIInfo.type = dr["科室类型名称"].ToString();
                            HDIInfo.opened = Convert.ToBoolean(dr["是否24小时开放"]);
                            HDIInfo.remark = dr["备注"].ToString();
                            HDIInfo.aidNum = Convert.ToInt32(dr["急诊出诊医生数"]);
                            HDIList.Add(HDIInfo);
                        }
                        var list = HDIList.GroupBy(q => q.type).Select(q => new
                        {
                            typeName = q.Key,
                            list = q.Select(t => new
                            {
                                name = t.name,
                                opened = t.opened,
                                remark = t.remark,
                                aidNum = t.aidNum
                            }).ToList()
                        }).ToList();
                        mainHT.Add("HDList", list);
                    }
                    if (ds.Tables[2].Rows.Count > 0)
                    {
                        List<HospitalAidableInfo> HAIList = new List<HospitalAidableInfo>();
                        HospitalAidableInfo HAIInfo;
                        foreach (DataRow dr in ds.Tables[2].Rows)
                        {
                            HAIInfo = new HospitalAidableInfo();
                            HAIInfo.name = dr["能力名称"].ToString();
                            HAIInfo.type = dr["能力类型名称"].ToString();
                            HAIInfo.opened = Convert.ToBoolean(dr["是否24小时开放"]);
                            HAIInfo.remark = dr["备注"].ToString();
                            HAIList.Add(HAIInfo);
                        }
                        var list = HAIList.GroupBy(q => q.type).Select(q => new
                        {
                            typeName = q.Key,
                            list = q.Select(t => new
                            {
                                name = t.name,
                                opened = t.opened,
                                remark = t.remark
                            }).ToList()
                        }).ToList();
                        mainHT.Add("HAList", list);
                    }
                    ri.data = mainHT;
                }
                else
                {
                    ri.ret = false;
                    ri.res = "未获取到医院相关信息";
                }
            }
            catch (Exception ex)
            {
                ri.ret = false;
                ri.res = ex.Message;
                LogUtility.Error("HospitalBLL/GetHospitalInfo", ex.ToString());
            }
            return ri;
        }
        public double DealDataToPercent(object val, object sum)
        {
            double ret = 0;
            if (!(val is DBNull) && !(sum is DBNull))
            {
                int intSum = Convert.ToInt32(sum.ToString());
                if (intSum != 0)
                {
                    int intVal = Convert.ToInt32(val.ToString());
                    double dblVal = intVal * 100.0 / intSum;
                    ret = Math.Round(dblVal, 0, MidpointRounding.AwayFromZero);
                }
            }
            return ret;
        }
        //public RetInfo<string> FilterHospital(ServerParamsInfo info)
        //{
        //    RetInfo<string> ri = new RetInfo<string>(true);
        //    try
        //    {
        //        SaveServerInfo.Instatnce.SaveServerParamsInfo(info);
        //        LogUtility.Debug("FilterHospital", JsonConvert.SerializeObject(info));
        //        WSRetInfo<string> wsri = new WSRetInfo<string>();
        //        wsri.type = "FilterHospital";
        //        wsri.data = info.PatientKind;
        //        DealICDataBLL.Instance.wsis.FindAll(q => q.AmbCode.Equals(info.AmbID)).
        //            ForEach(q => q.WebSocket.Send(JsonConvert.SerializeObject(wsri)));
        //        //DealICDataBLL.Instance.wsis.ForEach(q => q.WebSocket.Send(JsonConvert.SerializeObject(wsri)));
        //        ri.data = "筛选医院成功";
        //    }
        //    catch (Exception ex)
        //    {
        //        ri.res = ex.Message;
        //        ri.ret = false;
        //        LogUtility.Error("HospitalBLL/FilterHospital", ex.ToString());
        //        //throw;
        //    }
        //    return ri;
        //}


        //public RetInfo<string> SendHospitalToServer(ServerParamsInfo info)
        //{
        //    RetInfo<string> ri = new RetInfo<string>(true);
        //    try
        //    {
        //        List<ServerParamsInfo> list = SaveServerInfo.Instatnce.GetServerParamsList()
        //            .FindAll(q => q.AmbID == info.AmbID);
        //        LogUtility.Debug("SendHospitalToServer", JsonConvert.SerializeObject(info));
        //        //List<ServerParamsInfo> list = SaveServerInfo.Instatnce.GetServerParamsList();
        //        if (list.Count > 0)
        //        {
        //            list.ForEach(q => {
        //                q.HospitalId = info.HospitalId;
        //                q.HospitalName = info.HospitalName;
        //            });
        //            string param = string.Format("type=RqstToldByWeb&Content={0}", JsonConvert.SerializeObject(list.FirstOrDefault()));
        //            string res = HttpUtils.PostWebRequest(WebConfig.GetAppSetStr("ServerHttpUrl"), Encoding.UTF8, param);
        //            ServerRetInfo sri = JsonConvert.DeserializeObject<ServerRetInfo>(res);
        //            if (sri.Status == "-1")
        //            {
        //                ri.ret = false;
        //                ri.res = sri.ResMsg;
        //            }
        //            else
        //            {
        //                ri.data = sri.ResMsg;
        //            }
        //        }
        //        else
        //        {
        //            ri.ret = false;
        //            ri.res = "请在APP上选择病种后在选择医院";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ri.res = ex.Message;
        //        ri.ret = false;
        //        LogUtility.Error("HospitalBLL/SendHospitalToServer", ex.ToString());
        //        //throw;
        //    }
        //    return ri;
        //}
    }
}
